package com.chookss.tiku

import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.view.View
import android.widget.ImageView
import android.widget.TextView
import androidx.lifecycle.ViewModelProviders
import androidx.recyclerview.widget.LinearLayoutManager
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.viewholder.BaseViewHolder
import com.chookss.R
import com.chookss.tiku.entity.Subject
import com.chookss.tools.MyToast
import com.chookss.tools.Utils
import com.chookss.view.RecycleViewDivider
import com.johnrambo.ktea.ktExtends.observe
import errorToast
import kotlinx.android.synthetic.main.activity_answer_exam.*
import kotlinx.android.synthetic.main.activity_practice_test_base.*
import kotlinx.android.synthetic.main.activity_practice_test_base.tvActivityTitle
import kotlinx.android.synthetic.main.view_subject.*
import java.io.Serializable
import java.util.ArrayList

/**答题结果解析页面
 */
class ExamRecordSubjectListActivity : BasePracticeTestActivity<ExamRecordSubjectViewModel>() {
    var name:String?=null
    var subjectAdapter: TitleAdapter? = null
    var memoryAdapter: TitleAdapter? = null
    private val subjectList = ArrayList<HashMap<String, String>>()
    private val memoryList = ArrayList<HashMap<String, String>>()
    var selectSubject = ArrayList<String>()
    var selectMemory = ArrayList<String>()
    override fun createViewModel(): ExamRecordSubjectViewModel {
        return ViewModelProviders.of(this).get(ExamRecordSubjectViewModel::class.java).apply {
            examCode = intent?.getStringExtra("examCode") ?: ""
            practiceType = intent?.getStringExtra("practiceType") ?: ""
            periodName = intent?.getStringExtra("periodName") ?: ""
            recordUid = intent?.getStringExtra("recordUid") ?: ""
            name = intent?.getStringExtra("title") ?: ""
            isMiss = intent?.getStringExtra("isMiss") ?: ""
            memoryLvl=""
            subjectTypeCode=""
        }
    }


    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        tvActivityTitle.text = name
        sourceType= intent.getStringExtra("practiceType").toString()
        subjectView().showSubjectNext=2
        topBar.visibility = View.VISIBLE
        tvTopBarRight.text="用时："+intent.getStringExtra("time")
        subjectView().enableAnswers = false
        subjectView().showSubmit = false
        llFloatBtns.visibility = View.VISIBLE
        if("1".equals(sourceType)||"2".equals(sourceType)||"5".equals(sourceType)){
            tvDatika.visibility = View.GONE
            ivSubjectShaixuan.visibility = View.VISIBLE
        }else{
            tvDatika.visibility = View.VISIBLE
        }
        ivMemory.visibility = View.VISIBLE
        tvError.visibility = View.VISIBLE
        tvCollect.visibility = View.VISIBLE
        tvShare.visibility = View.VISIBLE
        tvDatika.setOnClickListener {
            var subjects = viewModel.subjectLists
            var intent = Intent(this, AnswerCardActivity::class.java)
            intent.putExtra("subjects", subjects as Serializable?)
            intent.putExtra("title",tvActivityTitle.text.toString())
            intent.putExtra("type",1)
            startActivityForResult(intent, 1)
        }
        tvSubjectNext.setOnClickListener {
            gotoSubject(subjectIndex + 1)
        }
        initRvs()
    }
    private fun initRvs() {
        rvSubject.setLayoutManager(
            LinearLayoutManager(
                mContext,
                LinearLayoutManager.VERTICAL,
                false
            )
        )
        rvSubject.addItemDecoration(
            RecycleViewDivider(
                this, LinearLayoutManager.HORIZONTAL, Utils.dip2px(this, 0.5f), resources.getColor(
                    R.color.line_gray
                )
            )
        )
        rvMemory.setLayoutManager(
            LinearLayoutManager(
                mContext,
                LinearLayoutManager.VERTICAL,
                false
            )
        )
        rvMemory.addItemDecoration(
            RecycleViewDivider(
                this, LinearLayoutManager.HORIZONTAL, Utils.dip2px(this, 0.5f), resources.getColor(
                    R.color.line_gray
                )
            )
        )
        val map: HashMap<String, String> = HashMap()
        map.put("title", "单选题")
        map.put("data", "1001")
        map.put("select", "false")
        subjectList.add(map)
        val map2: HashMap<String, String> = HashMap()
        map2.put("title", "多选题")
        map2.put("data", "1002")
        map2.put("select", "false")
        subjectList.add(map2)
        val map3: HashMap<String, String> = HashMap()
        map3.put("title", "判断题")
        map3.put("data", "1003")
        map3.put("select", "false")
        subjectList.add(map3)
        val map4: HashMap<String, String> = HashMap()
        map4.put("title", "填空题")
        map4.put("data", "1004")
        map4.put("select", "false")
        subjectList.add(map4)
        val map5: HashMap<String, String> = HashMap()
        map5.put("title", "问答题")
        map5.put("data", "1005")
        map5.put("select", "false")
        subjectList.add(map5)
        val memoryMap: HashMap<String, String> = HashMap()
        memoryMap.put("title", "未记忆")
        memoryMap.put("data", "01")
        memoryMap.put("select", "false")
        memoryList.add(memoryMap)
        val memoryMap2: HashMap<String, String> = HashMap()
        memoryMap2.put("title", "开始记忆")
        memoryMap2.put("data", "02")
        memoryMap2.put("select", "false")
        memoryList.add(memoryMap2)
        val memoryMap3: HashMap<String, String> = HashMap()
        memoryMap3.put("title", "正在巩固")
        memoryMap3.put("data", "03")
        memoryMap3.put("select", "false")
        memoryList.add(memoryMap3)
        val memoryMap4: HashMap<String, String> = HashMap()
        memoryMap4.put("title", "已牢记")
        memoryMap4.put("data", "04")
        memoryMap4.put("select", "false")
        memoryList.add(memoryMap4)
        val memoryMap5: HashMap<String, String> = HashMap()
        memoryMap5.put("title", "开始遗忘")
        memoryMap5.put("data", "05")
        memoryMap5.put("select", "false")
        memoryList.add(memoryMap5)
        val memoryMap6: HashMap<String, String> = HashMap()
        memoryMap6.put("title", "已遗忘")
        memoryMap6.put("data", "06")
        memoryMap6.put("select", "false")
        memoryList.add(memoryMap6)
        subjectAdapter = TitleAdapter(R.layout.item_subject_choice, this, subjectList)
        rvSubject.setAdapter(subjectAdapter)
        memoryAdapter = TitleAdapter(R.layout.item_subject_choice, this, memoryList)
        rvMemory.setAdapter(memoryAdapter)
        subjectAdapter!!.setOnItemClickListener { adapter, view, position ->
            if (subjectList.get(position).get("select").equals("true")) {
                subjectList.get(position).put("select", "false")
                selectSubject.remove(subjectList.get(position).get("data"));
            } else {
                subjectList.get(position).put("select", "true")
                selectSubject.add(subjectList.get(position).get("data").toString())
            }
            var subjectTypeCode: String? = null
            for (i in 0 until selectSubject.size) {
                if (i == 0) {
                    subjectTypeCode = selectSubject.get(i)
                } else {
                    subjectTypeCode = subjectTypeCode + "," + selectSubject.get(i)
                }
            }
            adapter.notifyDataSetChanged()
            println(subjectTypeCode.toString())
            viewModel.subjectTypeCode = subjectTypeCode.toString()
            subjectIndex = 0
            gotoSubject(subjectIndex )
            rlType.visibility = View.GONE
            rvSubject.visibility = View.GONE
            if (selectSubject.size > 0) {
                ivSubjectShaixuan.setBackgroundResource(R.drawable.tx_sx_sel)
            } else {
                ivSubjectShaixuan.setBackgroundResource(R.drawable.tx_sx_unsel)
            }
        }
        memoryAdapter!!.setOnItemClickListener { adapter, view, position ->
            if (memoryList.get(position).get("select").equals("true")) {
                memoryList.get(position).put("select", "false")
                selectMemory.remove(memoryList.get(position).get("data"));
            } else {
                memoryList.get(position).put("select", "true")
                selectMemory.add(memoryList.get(position).get("data").toString())
            }
            var memoryLvl: String? = null
            for (i in 0 until selectMemory.size) {
                if (i == 0) {
                    memoryLvl = selectMemory.get(i)
                } else {
                    memoryLvl = memoryLvl + "," + selectMemory.get(i)
                }
            }
            adapter.notifyDataSetChanged()
            viewModel.memoryLvl = memoryLvl.toString()
            subjectIndex = 0
            gotoSubject(subjectIndex )
            rlType.visibility = View.GONE
            rvMemory.visibility = View.GONE
            if(selectMemory.size>0){
                ivMemory.setBackgroundResource(R.drawable.icon_ywqx_sel)
            }else{
                ivMemory.setBackgroundResource(R.drawable.icon_ywqx_unsel)
            }
        }
    }
    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (resultCode == 1) {
            if (data != null) {
                var index: Int = data.getIntExtra("index", 0)
                gotoSubject(index)
            }
        }
    }

    override fun onSubjectLoaded(index: Int, subject: Subject) {
        super.onSubjectLoaded(index, subject)
        bottom_ll.visibility = View.GONE

        if(subject?.subjectTypeCode.equals("1004")){
            subjectView().updateMyAnswers(subject!!.optionLvlNo.split("@#^"))
        }else if(subject?.subjectTypeCode.equals("1005")){
            var value: ArrayList<String> = ArrayList()
            value.add(subject!!.optionLvlNo)
            subjectView().updateMyAnswers(value)
        }else{
            subjectView().updateMyAnswers(subject.optionLvlNo?.split(","))
        }
        subjectView().showRightAnswerInfo()
        getSubjectDetail()
        tvTopBarLeft.text=""+(index+1)+"/"+viewModel.subjectLists.size
        println(viewModel.subjectLists.size)
    }
    fun getSubjectDetail() {
        viewModel.getRecordUidSubjectDetail(subjectView().subject?.answerId.toString(), subjectView().subject!!)
            .observe(this, {
                loadingProgress.dismiss()
                if (it.error != null) {
                    errorToast(it.error.message ?: "")
                } else {
                    subjectView().showRightAnswerInfo()
                    onAnswerSubmited(
                        subjectIndex,
                        subjectView().subject!!,
                        subjectView().myAnswers
                    )
                    isShowAnswer = true
                    subjectView().showAnswerDetail(it.data)
                }
            })
    }

    override fun onShowSubjectsLoaded(isShowData: Boolean) {
        if (isShowData) {
            llFloatBtns.visibility = View.VISIBLE
            if("1".equals(sourceType)||"2".equals(sourceType)||"5".equals(sourceType)){
                tvDatika.visibility = View.GONE
                ivSubjectShaixuan.visibility = View.VISIBLE
            }else{
                tvDatika.visibility = View.VISIBLE
            }
            ivMemory.visibility = View.VISIBLE
            tvError.visibility = View.VISIBLE
            tvCollect.visibility = View.VISIBLE
            tvShare.visibility = View.VISIBLE
            topBar.visibility = View.VISIBLE
            subjectScrollView.visibility = View.VISIBLE
            llEmpty.visibility = View.GONE
        } else {
            if(viewModel.subjectLists.size>0){
              MyToast.show("已经是最后一题了")
                subjectIndex=0;
                gotoSubject(subjectIndex)
            }else{
                llFloatBtns.visibility = View.INVISIBLE
                subjectScrollView.visibility = View.INVISIBLE
                topBar.visibility = View.INVISIBLE
                ivNext.visibility=View.INVISIBLE
                llEmpty.visibility = View.VISIBLE
                tvEmptyView1.text = "暂无数据"
                tvEmptyView2.text = "快去题库参与答题吧"
            }

        }

    }

    override fun initData() {
    }
    class TitleAdapter(
        layoutResId: Int,
        context: Context,
        data: ArrayList<HashMap<String, String>>
    ) : BaseQuickAdapter<HashMap<String, String>, BaseViewHolder>(layoutResId, data) {

        override fun convert(holder: BaseViewHolder, item: HashMap<String, String>) {
            val ivStatus = holder?.getView<ImageView>(R.id.ivStatus)
            val tvTiltle = holder?.getView<TextView>(R.id.tvTiltle)
            tvTiltle?.text = item?.get("title")
            if (item?.get("select").equals("true")) {
                tvTiltle?.isSelected = true
                ivStatus?.isSelected = true
            } else {
                tvTiltle?.isSelected = false
                ivStatus?.isSelected = false
            }
        }

    }
}